extends Node

## 幻兽管理器
## 负责管理幻兽系统，包括幻兽获得、升级、队伍管理、生命系统等功能

signal phantom_beast_obtained(beast_data: Dictionary)
signal phantom_beast_level_up(beast_id: String, new_level: int)
signal formation_changed(active_beasts: Array[Dictionary])
signal phantom_beast_health_changed(beast_id: String, current_hp: int, max_hp: int)
signal phantom_beast_died(beast_id: String)
signal phantom_beast_renamed(beast_id: String, new_name: String)

# 幻兽数据存储
var owned_phantom_beasts: Dictionary = {}  # 拥有的幻兽 {unique_beast_id: beast_data}
var active_formation: Array[String] = []  # 当前上阵的幻兽ID列表，最多4个
var max_formation_size: int = 4  # 最大上阵数量
var next_beast_id: int = 1  # 下一个幻兽的唯一ID

# 幻兽合成系统配置
var max_star_level: int = 10  # 最高星级
# 星级加成：每星级增加20%属性（在get_phantom_beast_stats中计算）
var synthesis_cost_base: int = 100  # 合成基础费用

# 幻兽获得概率配置
var base_capture_rate: float = 15.0  # 基础捕获概率15%
var rarity_capture_modifiers: Dictionary = {
	"common": 1.0,      # 普通怪物100%基础概率
	"uncommon": 0.7,    # 不常见怪物70%基础概率
	"rare": 0.4,        # 稀有怪物40%基础概率
	"epic": 0.2,        # 史诗怪物20%基础概率
	"legendary": 0.1    # 传说怪物10%基础概率
}

# 幻兽基础配置（从monsters.json动态加载）# 幻兽配置数据（包含成长率）
var phantom_beast_config: Dictionary = {}

# 幻兽成长配置
var level_exp_requirements: Array[int] = []
var max_phantom_beast_level: int = 50

func _ready():
	"""初始化幻兽管理器"""
	process_mode = Node.PROCESS_MODE_ALWAYS
	_initialize_exp_table()
	_load_phantom_beast_config()
	# 不再自动加载独立的幻兽数据文件，数据将通过GameSaveManager统一管理

func _initialize_exp_table():
	"""初始化经验值表"""
	level_exp_requirements.clear()
	level_exp_requirements.append(0)  # 1级不需要经验
	
	# 计算每级所需经验值
	for level in range(2, max_phantom_beast_level + 1):
		var exp_needed = int(pow(level, 2.2) * 10)
		level_exp_requirements.append(exp_needed)

func _load_phantom_beast_config():
	"""从monsters.json加载幻兽配置"""
	var file_path = "res://data/monsters/monsters.json"
	if not FileAccess.file_exists(file_path):
		print("错误：未找到怪物数据文件: ", file_path)
		return
	
	var file = FileAccess.open(file_path, FileAccess.READ)
	if file == null:
		print("错误：无法打开怪物数据文件: ", file_path)
		return
	
	var json_string = file.get_as_text()
	file.close()
	
	var json = JSON.new()
	var parse_result = json.parse(json_string)
	if parse_result != OK:
		print("错误：解析怪物数据文件失败: ", json.error_string)
		return
	
	var monsters_data = json.data
	if not monsters_data.has("monsters") or not monsters_data["monsters"] is Array:
		print("错误：怪物数据文件格式错误")
		return
	
	# 从怪物数据生成幻兽配置
	for monster_data in monsters_data["monsters"]:
		var monster_id = monster_data.get("id", "")
		if monster_id.is_empty():
			continue
		
		# 从JSON加载幻兽配置（包含基础属性和成长率）
		var phantom_config = monster_data.get("phantom_beast_growth_rates", {})
		if phantom_config.size() == 0:
			# 默认配置（如果JSON中没有配置）
			phantom_config = {
				"base_hp": int(monster_data.get("max_hp", 50) * 0.8),
				"base_attack": int(monster_data.get("attack", 10) * 0.8),
				"base_defense": int(monster_data.get("defense", 5) * 0.8),
				"base_attack_speed": monster_data.get("attack_speed", 100),
				"hp_growth": 0.1,
				"attack_growth": 0.1,
				"defense_growth": 0.1,
				"attack_speed_growth": 0.05
			}
		
		phantom_beast_config[monster_id] = {
			"name": monster_data.get("name", "未知幻兽") + "幼崽",
			"description": "来自 " + monster_data.get("name", "未知怪物") + " 的幼体",
			"base_stats": {
				"hp": phantom_config.get("base_hp", 50),
				"attack": phantom_config.get("base_attack", 10),
				"defense": phantom_config.get("base_defense", 5),
				"attack_speed": phantom_config.get("base_attack_speed", 100)
			},
			"growth_rates": {
				"hp": phantom_config.get("hp_growth", 0.1),
				"attack": phantom_config.get("attack_growth", 0.1),
				"defense": phantom_config.get("defense_growth", 0.1),
				"attack_speed": phantom_config.get("attack_speed_growth", 0.05)
			},
			"rarity": monster_data.get("rarity", "common"),
			"sprite_path": monster_data.get("phantom_beast_icon_path", monster_data.get("sprite_path", ""))
		}
	
	print("已加载 ", phantom_beast_config.size(), " 种幻兽配置")

func try_obtain_phantom_beast(monster_data: Dictionary, force_obtain: bool = false) -> bool:
	"""尝试获得幻兽（战斗胜利后调用）"""
	if not monster_data.has("id") or not monster_data.has("rarity"):
		print("错误：怪物数据不完整，无法获得幻兽")
		return false
	
	var rarity = monster_data["rarity"]
	
	# 如果强制获得，跳过概率检定
	if force_obtain:
		var beast_data = _create_phantom_beast_from_monster(monster_data)
		var unique_id = _generate_unique_beast_id()
		beast_data["unique_id"] = unique_id
		owned_phantom_beasts[unique_id] = beast_data
		phantom_beast_obtained.emit(beast_data)
		print("强制获得幻兽: %s (Lv.1)" % beast_data.name)
		# 数据将在下次自动保存或手动保存时保存
		return true
	
	# 计算捕获概率
	var capture_chance = _calculate_capture_chance(rarity)
	var roll = randf() * 100.0
	
	print("幻兽捕获检定: %.1f%% (需要 <= %.1f%%)" % [roll, capture_chance])
	
	if roll <= capture_chance:
		# 成功获得幻兽
		var beast_data = _create_phantom_beast_from_monster(monster_data)
		var unique_id = _generate_unique_beast_id()
		beast_data["unique_id"] = unique_id
		owned_phantom_beasts[unique_id] = beast_data
		phantom_beast_obtained.emit(beast_data)
		print("成功获得幻兽: %s (Lv.1)" % beast_data.name)
		# 数据将在下次自动保存或手动保存时保存
		return true
	else:
		print("幻兽捕获失败")
		return false

func _calculate_capture_chance(rarity: String) -> float:
	"""计算捕获概率"""
	var modifier = rarity_capture_modifiers.get(rarity, 1.0)
	return base_capture_rate * modifier

func _generate_unique_beast_id() -> String:
	"""生成唯一的幻兽ID"""
	var unique_id = "beast_" + str(next_beast_id)
	next_beast_id += 1
	return unique_id

func _create_phantom_beast_from_monster(monster_data: Dictionary) -> Dictionary:
	"""从怪物数据创建幻兽数据"""
	var monster_id = monster_data["id"]
	var config = phantom_beast_config.get(monster_id, {})
	
	# 获取幻兽的基础属性（不再依赖怪物属性的80%）
	var base_stats = config.get("base_stats", {})
	var base_hp = base_stats.get("hp", 50)
	var base_attack = base_stats.get("attack", 10)
	var base_defense = base_stats.get("defense", 5)
	var base_attack_speed = base_stats.get("attack_speed", 100)
	
	return {
		"monster_type": monster_id,  # 怪物类型ID，用于识别幻兽种类
		"name": monster_data.get("name", "未知幻兽"),
		"custom_name": "",  # 自定义名称，为空时使用默认名称
		"level": 1,
		"current_exp": 0,
		"star_level": 1,  # 星级，初始为1星
		"base_hp": base_hp,
		"current_hp": base_hp,  # 当前生命值
		"max_hp": base_hp,  # 最大生命值（会随等级增长）
		"base_attack": base_attack,
		"base_defense": base_defense,
		"attack_speed": base_attack_speed,
		"sprite_path": monster_data.get("sprite_path", ""),
		"icon_path": monster_data.get("phantom_beast_icon_path", monster_data.get("sprite_path", "")),
		"rarity": monster_data.get("rarity", "common"),
		"description": "来自 " + monster_data.get("name", "未知怪物") + " 的幼崽",
		"obtained_time": Time.get_unix_time_from_system(),
		"is_alive": true  # 生存状态
	}

func gain_phantom_beast_exp(beast_id: String, exp_amount: int):
	"""为幻兽增加经验值"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return
	
	var beast_data = owned_phantom_beasts[beast_id]
	var beast_level = beast_data["level"]
	
	# 检查幻兽等级是否高于玩家等级2级
	var player_level = 1  # 默认玩家等级
	if PlayerStatsManager != null:
		player_level = PlayerStatsManager.get_level()
	
	# 如果幻兽等级高于玩家等级2级，则不获得经验
	if beast_level > player_level + 2:
		print("幻兽 %s (Lv.%d) 等级过高，无法获得经验 (玩家等级: %d)" % [get_phantom_beast_display_name(beast_id), beast_level, player_level])
		return
	
	var old_level = beast_data["level"]
	beast_data["current_exp"] += exp_amount
	
	# 检查是否升级
	var new_level = _calculate_level_from_exp(beast_data["current_exp"])
	if new_level > old_level and new_level <= max_phantom_beast_level:
		beast_data["level"] = new_level
		# 升级时更新生命值
		update_phantom_beast_hp_on_level_up(beast_id)
		phantom_beast_level_up.emit(beast_id, new_level)
		print("幻兽 %s 升级到 Lv.%d!" % [get_phantom_beast_display_name(beast_id), new_level])
	
	# 数据将在下次自动保存或手动保存时保存

func add_phantom_beast_experience(beast_id: String, exp_amount: int):
	"""为幻兽增加经验值（与gain_phantom_beast_exp功能相同，提供兼容性）"""
	gain_phantom_beast_exp(beast_id, exp_amount)

func _calculate_level_from_exp(total_exp: int) -> int:
	"""根据总经验值计算等级"""
	for level in range(max_phantom_beast_level, 0, -1):
		if level == 1 or total_exp >= level_exp_requirements[level - 1]:
			return level
	return 1

func get_phantom_beast_stats(beast_id: String) -> Dictionary:
	"""获取幻兽的当前属性"""
	if not owned_phantom_beasts.has(beast_id):
		return {}
	
	var beast_data = owned_phantom_beasts[beast_id]
	var level = beast_data["level"]
	var star_level = beast_data.get("star_level", 1)
	var monster_type = beast_data.get("monster_type", "")
	
	# 获取该幻兽类型的成长率配置
	var growth_rates = {"hp": 0.1, "attack": 0.1, "defense": 0.1, "attack_speed": 0.05}
	if phantom_beast_config.has(monster_type) and phantom_beast_config[monster_type].has("growth_rates"):
		growth_rates = phantom_beast_config[monster_type]["growth_rates"]
	
	# 根据星级计算属性加成
	var star_bonus = (star_level - 1) * 0.2  # 每星级增加20%属性
	
	# 根据成长率和等级计算属性倍数（线性增长）
	var hp_multiplier = 1.0 + (growth_rates.get("hp", 0.1) * (level - 1)) * (1.0 + star_bonus)
	var attack_multiplier = 1.0 + (growth_rates.get("attack", 0.1) * (level - 1)) * (1.0 + star_bonus)
	var defense_multiplier = 1.0 + (growth_rates.get("defense", 0.1) * (level - 1)) * (1.0 + star_bonus)
	var attack_speed_multiplier = 1.0 + (growth_rates.get("attack_speed", 0.05) * (level - 1))
	
	# 计算当前属性
	var calculated_max_hp = int(beast_data["base_hp"] * hp_multiplier)
	var calculated_attack = int(beast_data["base_attack"] * attack_multiplier)
	var calculated_defense = int(beast_data["base_defense"] * defense_multiplier)
	var calculated_attack_speed = int(beast_data["attack_speed"] * attack_speed_multiplier)
	
	return {
		"max_hp": calculated_max_hp,
		"current_hp": beast_data.get("current_hp", calculated_max_hp),
		"attack": calculated_attack,
		"defense": calculated_defense,
		"attack_speed": calculated_attack_speed,
		"level": level,
		"is_alive": beast_data.get("is_alive", true)
	}

func add_to_formation(beast_id: String) -> bool:
	"""将幻兽加入上阵队伍"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未拥有幻兽 %s" % beast_id)
		return false
	
	if active_formation.has(beast_id):
		print("幻兽 %s 已在队伍中" % beast_id)
		return false
	
	if active_formation.size() >= max_formation_size:
		print("队伍已满，无法添加更多幻兽")
		return false
	
	active_formation.append(beast_id)
	formation_changed.emit(get_active_formation_data())
	# 数据将在下次自动保存或手动保存时保存
	print("幻兽 %s 加入队伍" % owned_phantom_beasts[beast_id]["name"])
	return true

func remove_from_formation(beast_id: String) -> bool:
	"""将幻兽从上阵队伍移除"""
	var index = active_formation.find(beast_id)
	if index == -1:
		print("幻兽 %s 不在队伍中" % beast_id)
		return false
	
	active_formation.remove_at(index)
	formation_changed.emit(get_active_formation_data())
	# 数据将在下次自动保存或手动保存时保存
	print("幻兽 %s 离开队伍" % owned_phantom_beasts[beast_id]["name"])
	return true

func add_to_formation_at_position(beast_id: String, position: int) -> bool:
	"""将幻兽加入到队伍的指定位置"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未拥有幻兽 %s" % beast_id)
		return false
	
	if active_formation.has(beast_id):
		# 如果已在队伍中，先移除
		remove_from_formation(beast_id)
	
	# 确保队伍数组有足够的位置
	while active_formation.size() <= position:
		active_formation.append("")
	
	# 如果目标位置有幻兽，先移除
	if position < active_formation.size() and active_formation[position] != "":
		remove_from_formation(active_formation[position])
	
	# 在指定位置插入幻兽
	if position < active_formation.size():
		active_formation[position] = beast_id
	else:
		active_formation.append(beast_id)
	
	# 清理空字符串
	for i in range(active_formation.size() - 1, -1, -1):
		if active_formation[i] == "":
			active_formation.remove_at(i)
	
	formation_changed.emit(get_active_formation_data())
	# 数据将在下次自动保存或手动保存时保存
	print("幻兽 %s 加入队伍位置 %d" % [owned_phantom_beasts[beast_id]["name"], position + 1])
	return true

func remove_beast(beast_id: String) -> bool:
	"""完全移除幻兽（丢弃功能）"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未拥有幻兽 %s" % beast_id)
		return false
	
	# 从队伍中移除（如果在队伍中）
	if active_formation.has(beast_id):
		remove_from_formation(beast_id)
	
	# 从拥有列表中移除
	var beast_name = owned_phantom_beasts[beast_id]["name"]
	owned_phantom_beasts.erase(beast_id)
	
	# 数据将在下次自动保存或手动保存时保存
	print("幻兽 %s 已被丢弃" % beast_name)
	return true

func sell_phantom_beast(beast_id: String) -> bool:
	"""卖出幻兽并获得金币"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未拥有幻兽 %s" % beast_id)
		return false
	
	# 计算卖出价格
	var sell_price = calculate_sell_price(beast_id)
	
	# 从队伍中移除（如果在队伍中）
	if active_formation.has(beast_id):
		remove_from_formation(beast_id)
	
	# 获得金币
	if PlayerStatsManager != null:
		PlayerStatsManager.add_gold(sell_price)
	
	# 从拥有列表中移除
	var beast_name = get_phantom_beast_display_name(beast_id)
	owned_phantom_beasts.erase(beast_id)
	
	# 数据将在下次自动保存或手动保存时保存
	print("幻兽 %s 已卖出，获得 %d 金币" % [beast_name, sell_price])
	return true

func calculate_sell_price(beast_id: String) -> int:
	"""计算幻兽卖出价格"""
	if not owned_phantom_beasts.has(beast_id):
		return 0
	
	var beast_data = owned_phantom_beasts[beast_id]
	var level = beast_data.get("level", 1)
	var monster_type = beast_data.get("monster_type", "")
	
	# 基础价格根据稀有度确定
	var base_price = 10
	var config = get_phantom_beast_config(monster_type)
	if not config.is_empty():
		var rarity = config.get("rarity", "common")
		match rarity:
			"common":
				base_price = 10
			"uncommon":
				base_price = 25
			"rare":
				base_price = 50
			"epic":
				base_price = 100
			"legendary":
				base_price = 200
	
	# 等级加成：每级增加基础价格的50%
	var level_bonus = int(base_price * 0.5 * (level - 1))
	
	# 如果幻兽已死亡，价格减半
	var death_penalty = 1.0
	if not beast_data.get("is_alive", true):
		death_penalty = 0.5
	
	return int((base_price + level_bonus) * death_penalty)

func calculate_revive_cost(beast_id: String) -> int:
	"""计算幻兽复活费用"""
	if not owned_phantom_beasts.has(beast_id):
		return 0
	
	var beast_data = owned_phantom_beasts[beast_id]
	var level = beast_data.get("level", 1)
	var monster_type = beast_data.get("monster_type", "")
	
	# 基础复活费用根据稀有度确定
	var base_cost = 20
	var config = get_phantom_beast_config(monster_type)
	if not config.is_empty():
		var rarity = config.get("rarity", "common")
		match rarity:
			"common":
				base_cost = 20
			"uncommon":
				base_cost = 40
			"rare":
				base_cost = 80
			"epic":
				base_cost = 150
			"legendary":
				base_cost = 300
	
	# 等级加成：每级增加基础费用的30%
	var level_bonus = int(base_cost * 0.3 * (level - 1))
	
	return base_cost + level_bonus

func get_active_formation_data() -> Array[Dictionary]:
	"""获取当前上阵幻兽的详细数据"""
	var formation_data: Array[Dictionary] = []
	for beast_id in active_formation:
		if owned_phantom_beasts.has(beast_id):
			var beast_data = owned_phantom_beasts[beast_id].duplicate()
			beast_data["stats"] = get_phantom_beast_stats(beast_id)
			formation_data.append(beast_data)
	return formation_data



func get_formation_battle_bonus() -> Dictionary:
	var total_bonus = {
		"hp_bonus": 0,
		"attack_bonus": 0,
		"defense_bonus": 0
	}
	
	return total_bonus

# 移除独立的幻兽数据保存函数，数据现在通过GameSaveManager统一保存
# func save_phantom_beast_data() - 已废弃，使用GameSaveManager.save_game_to_slot()

# 移除独立的幻兽数据加载函数，数据现在通过GameSaveManager统一加载
# func load_phantom_beast_data() - 已废弃，使用GameSaveManager.load_game_from_slot()

func get_phantom_beast_count() -> int:
	"""获取拥有的幻兽数量"""
	return owned_phantom_beasts.size()

func get_all_owned_beasts() -> Array[Dictionary]:
	"""获取所有拥有的幻兽完整信息"""
	var all_beasts: Array[Dictionary] = []
	for beast_id in owned_phantom_beasts.keys():
		var full_info = get_phantom_beast_full_info(beast_id)
		if not full_info.is_empty():
			all_beasts.append(full_info)
	return all_beasts

func sort_phantom_beasts() -> Array[Dictionary]:
	"""整理幻兽背包：按照怪物种类、等级、星级排序，并重新组织存储顺序"""
	var all_beasts = get_all_owned_beasts()
	
	# 自定义排序函数
	all_beasts.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
		# 首先按怪物种类排序
		var type_a = a.get("monster_type", "")
		var type_b = b.get("monster_type", "")
		if type_a != type_b:
			return type_a < type_b
		
		# 同种类按星级排序（高星级在前）
		var star_a = a.get("star_level", 1)
		var star_b = b.get("star_level", 1)
		if star_a != star_b:
			return star_a > star_b
		
		# 同星级按等级排序（高等级在前）
		var level_a = a.get("level", 1)
		var level_b = b.get("level", 1)
		return level_a > level_b
	)
	
	# 重新组织owned_phantom_beasts字典的存储顺序
	_reorganize_owned_beasts_by_sorted_order(all_beasts)
	
	print("幻兽背包已整理完成")
	return all_beasts

func _reorganize_owned_beasts_by_sorted_order(sorted_beasts: Array[Dictionary]):
	"""根据排序后的幻兽列表重新组织owned_phantom_beasts字典的存储顺序"""
	# 备份原始数据
	var original_beasts = owned_phantom_beasts.duplicate()
	
	# 清空原字典
	owned_phantom_beasts.clear()
	
	# 按照排序后的顺序重新添加幻兽数据
	for beast_info in sorted_beasts:
		var beast_id = beast_info.get("unique_id", "")
		if beast_id != "" and original_beasts.has(beast_id):
			# 将原始数据按新顺序重新添加到字典中
			owned_phantom_beasts[beast_id] = original_beasts[beast_id]
	
	print("幻兽存储顺序已重新组织，共整理了 %d 只幻兽" % owned_phantom_beasts.size())

func get_phantom_beasts_by_type(monster_type: String) -> Array[Dictionary]:
	"""获取指定类型的所有幻兽"""
	var beasts_of_type: Array[Dictionary] = []
	for beast_id in owned_phantom_beasts.keys():
		var beast_data = owned_phantom_beasts[beast_id]
		if beast_data.get("monster_type", "") == monster_type:
			var full_data = get_phantom_beast_full_info(beast_id)
			beasts_of_type.append(full_data)
	return beasts_of_type

func get_phantom_beast_types_count() -> Dictionary:
	"""获取每种类型幻兽的数量统计"""
	var type_counts: Dictionary = {}
	for beast_data in owned_phantom_beasts.values():
		var monster_type = beast_data.get("monster_type", "unknown")
		if type_counts.has(monster_type):
			type_counts[monster_type] += 1
		else:
			type_counts[monster_type] = 1
	return type_counts

func get_formation_size() -> int:
	"""获取当前上阵幻兽数量"""
	return active_formation.size()

func has_phantom_beast(beast_id: String) -> bool:
	"""检查是否拥有指定幻兽"""
	return owned_phantom_beasts.has(beast_id)

func get_phantom_beast_data(beast_id: String) -> Dictionary:
	"""获取指定幻兽的数据"""
	if owned_phantom_beasts.has(beast_id):
		var beast_data = owned_phantom_beasts[beast_id].duplicate()
		beast_data["stats"] = get_phantom_beast_stats(beast_id)
		beast_data["in_formation"] = active_formation.has(beast_id)
		return beast_data
	return {}

func get_beast_by_id(beast_id: String) -> Dictionary:
	"""获取指定幻兽的完整信息（UI兼容函数）"""
	return get_phantom_beast_full_info(beast_id)

func set_capture_rate(new_rate: float):
	"""设置基础捕获概率"""
	base_capture_rate = clamp(new_rate, 0.0, 100.0)

func get_capture_rate() -> float:
	"""获取基础捕获概率"""
	return base_capture_rate

func get_formation_bonus() -> Dictionary:
	return get_formation_battle_bonus()

func get_active_formation_ids() -> Array:
	"""获取当前上阵幻兽的ID列表"""
	return active_formation.duplicate()

func set_phantom_beast_nickname(beast_id: String, new_nickname: String):
	"""设置幻兽昵称"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return
	
	var beast_data = owned_phantom_beasts[beast_id]
	var old_name = beast_data.get("custom_name", "")
	beast_data["custom_name"] = new_nickname.strip_edges()
	
	# 发送昵称修改信号
	phantom_beast_renamed.emit(beast_id, new_nickname)
	
	# 保存数据
	# 数据将在下次自动保存或手动保存时保存
	
	print("幻兽 %s 的昵称从 '%s' 修改为 '%s'" % [beast_id, old_name, new_nickname])



# ========== 幻兽生命系统 ==========

func update_phantom_beast_hp_on_level_up(beast_id: String):
	"""升级时更新幻兽最大生命值"""
	if not owned_phantom_beasts.has(beast_id):
		return
	
	var beast_data = owned_phantom_beasts[beast_id]
	var level = beast_data["level"]
	var star_level = beast_data.get("star_level", 1)
	var monster_type = beast_data.get("monster_type", "")
	
	# 获取该幻兽类型的成长率配置
	var growth_rates = {"hp": 0.1, "attack": 0.1, "defense": 0.1, "attack_speed": 0.05}
	if phantom_beast_config.has(monster_type) and phantom_beast_config[monster_type].has("growth_rates"):
		growth_rates = phantom_beast_config[monster_type]["growth_rates"]
	
	# 根据星级计算属性加成
	var star_bonus = (star_level - 1) * 0.2  # 每星级增加20%属性
	
	# 根据成长率和等级计算生命值倍数（线性增长）
	var hp_multiplier = 1.0 + (growth_rates.get("hp", 0.1) * (level - 1)) * (1.0 + star_bonus)
	
	# 计算新的最大生命值
	var new_max_hp = int(beast_data["base_hp"] * hp_multiplier)
	var old_max_hp = beast_data.get("max_hp", beast_data["base_hp"])
	
	# 更新最大生命值
	beast_data["max_hp"] = new_max_hp
	
	# 按比例增加当前生命值（如果幻兽还活着）
	if beast_data.get("is_alive", true):
		var hp_ratio = float(beast_data.get("current_hp", old_max_hp)) / float(old_max_hp)
		beast_data["current_hp"] = int(new_max_hp * hp_ratio)
		# 升级时额外恢复20%生命值
		var heal_amount = int(new_max_hp * 0.2)
		beast_data["current_hp"] = min(beast_data["current_hp"] + heal_amount, new_max_hp)
	
	phantom_beast_health_changed.emit(beast_id, beast_data["current_hp"], beast_data["max_hp"])
	# 数据将在下次自动保存或手动保存时保存

func heal_phantom_beast(beast_id: String, heal_amount: int) -> bool:
	"""治疗幻兽"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return false
	
	var beast_data = owned_phantom_beasts[beast_id]
	
	# 检查幻兽是否还活着
	if not beast_data.get("is_alive", true):
		print("无法治疗已死亡的幻兽: %s" % get_phantom_beast_display_name(beast_id))
		return false
	
	var stats = get_phantom_beast_stats(beast_id)
	var old_hp = beast_data.get("current_hp", stats["max_hp"])
	beast_data["current_hp"] = min(old_hp + heal_amount, stats["max_hp"])
	
	phantom_beast_health_changed.emit(beast_id, beast_data["current_hp"], stats["max_hp"])
	# 数据将在下次自动保存或手动保存时保存
	
	print("幻兽 %s 恢复了 %d 点生命值 (%d/%d)" % [
		get_phantom_beast_display_name(beast_id), 
		heal_amount, 
		beast_data["current_hp"], 
		stats["max_hp"]
	])
	return true

func damage_phantom_beast(beast_id: String, damage: int) -> bool:
	"""对幻兽造成伤害"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return false
	
	var beast_data = owned_phantom_beasts[beast_id]
	
	# 检查幻兽是否还活着
	if not beast_data.get("is_alive", true):
		print("无法对已死亡的幻兽造成伤害: %s" % get_phantom_beast_display_name(beast_id))
		return false
	
	var stats = get_phantom_beast_stats(beast_id)
	var old_hp = beast_data.get("current_hp", stats["max_hp"])
	beast_data["current_hp"] = max(0, old_hp - damage)
	
	# 检查是否死亡
	if beast_data["current_hp"] <= 0:
		beast_data["is_alive"] = false
		# 从队伍中移除死亡的幻兽
		if active_formation.has(beast_id):
			remove_from_formation(beast_id)
		phantom_beast_died.emit(beast_id)
		print("幻兽 %s 死亡了！" % get_phantom_beast_display_name(beast_id))
	
	phantom_beast_health_changed.emit(beast_id, beast_data["current_hp"], stats["max_hp"])
	# 数据将在下次自动保存或手动保存时保存
	return true

func revive_phantom_beast(beast_id: String, hp_percentage: float = 0.5) -> bool:
	"""复活幻兽"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return false
	
	var beast_data = owned_phantom_beasts[beast_id]
	
	# 检查幻兽是否已经死亡
	if beast_data.get("is_alive", true):
		print("幻兽 %s 还活着，无需复活" % get_phantom_beast_display_name(beast_id))
		return false
	
	var stats = get_phantom_beast_stats(beast_id)
	beast_data["is_alive"] = true
	beast_data["current_hp"] = int(stats["max_hp"] * clamp(hp_percentage, 0.1, 1.0))
	
	phantom_beast_health_changed.emit(beast_id, beast_data["current_hp"], stats["max_hp"])
	# 数据将在下次自动保存或手动保存时保存
	
	print("幻兽 %s 复活了！生命值: %d/%d" % [
		get_phantom_beast_display_name(beast_id), 
		beast_data["current_hp"], 
		stats["max_hp"]
	])
	return true

func heal_all_phantom_beasts_to_full():
	"""完全治疗所有幻兽"""
	for beast_id in owned_phantom_beasts.keys():
		var beast_data = owned_phantom_beasts[beast_id]
		if beast_data.get("is_alive", true):
			var stats = get_phantom_beast_stats(beast_id)
			beast_data["current_hp"] = stats["max_hp"]
			phantom_beast_health_changed.emit(beast_id, beast_data["current_hp"], stats["max_hp"])
	
	# 数据将在下次自动保存或手动保存时保存
	print("所有幻兽已完全恢复")

func heal_formation_on_walk():
	"""玩家移动时为上阵幻兽恢复少量生命值（按最大生命值百分比恢复）"""
	var heal_percentage = 0.02  # 恢复最大生命值的2%
	
	for beast_id in active_formation:
		if not owned_phantom_beasts.has(beast_id):
			continue
		
		var beast_data = owned_phantom_beasts[beast_id]
		
		# 只为活着的幻兽恢复生命值
		if not beast_data.get("is_alive", true):
			continue
		
		var stats = get_phantom_beast_stats(beast_id)
		var current_hp = beast_data.get("current_hp", stats["max_hp"])
		
		# 如果生命值未满，则恢复
		if current_hp < stats["max_hp"]:
			var heal_amount = max(1, int(stats["max_hp"] * heal_percentage))  # 至少恢复1点
			beast_data["current_hp"] = min(current_hp + heal_amount, stats["max_hp"])
			phantom_beast_health_changed.emit(beast_id, beast_data["current_hp"], stats["max_hp"])
	
	# 数据将在下次自动保存或手动保存时保存

func set_phantom_beast_hp(beast_id: String, new_hp: int) -> bool:
	"""直接设置幻兽的生命值（用于战斗结束后同步血量）"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return false
	
	var beast_data = owned_phantom_beasts[beast_id]
	var stats = get_phantom_beast_stats(beast_id)
	
	# 确保血量在有效范围内
	new_hp = max(0, min(new_hp, stats["max_hp"]))
	beast_data["current_hp"] = new_hp
	
	# 检查是否死亡
	if new_hp <= 0:
		beast_data["is_alive"] = false
		# 从队伍中移除死亡的幻兽
		if active_formation.has(beast_id):
			remove_from_formation(beast_id)
		phantom_beast_died.emit(beast_id)
		print("幻兽 %s 在战斗中死亡了！" % get_phantom_beast_display_name(beast_id))
	else:
		# 确保幻兽标记为活着
		beast_data["is_alive"] = true
	
	phantom_beast_health_changed.emit(beast_id, beast_data["current_hp"], stats["max_hp"])
	# 数据将在下次自动保存或手动保存时保存
	
	print("幻兽 %s 血量已更新: %d/%d" % [
		get_phantom_beast_display_name(beast_id), 
		beast_data["current_hp"], 
		stats["max_hp"]
	])
	return true

func get_phantom_beast_hp_percentage(beast_id: String) -> float:
	"""获取幻兽生命值百分比"""
	if not owned_phantom_beasts.has(beast_id):
		return 0.0
	
	var beast_data = owned_phantom_beasts[beast_id]
	if not beast_data.get("is_alive", true):
		return 0.0
	
	var stats = get_phantom_beast_stats(beast_id)
	if stats["max_hp"] <= 0:
		return 0.0
	
	return float(beast_data.get("current_hp", stats["max_hp"])) / float(stats["max_hp"])

func is_phantom_beast_alive(beast_id: String) -> bool:
	"""检查幻兽是否还活着"""
	if not owned_phantom_beasts.has(beast_id):
		return false
	
	var beast_data = owned_phantom_beasts[beast_id]
	return beast_data.get("is_alive", true) and beast_data.get("current_hp", 0) > 0

# ========== 幻兽改名系统 ==========

func rename_phantom_beast(beast_id: String, new_name: String) -> bool:
	"""为幻兽改名"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return false
	
	# 验证名称
	var trimmed_name = new_name.strip_edges()
	if trimmed_name.length() == 0:
		print("错误：幻兽名称不能为空")
		return false
	
	if trimmed_name.length() > 20:
		print("错误：幻兽名称不能超过20个字符")
		return false
	
	# 检查是否包含非法字符
	var forbidden_chars = ["<", ">", "&", "'", '"', "\n", "\t"]
	for forbidden_char in forbidden_chars:
		if trimmed_name.contains(forbidden_char):
			print("错误：幻兽名称包含非法字符: %s" % forbidden_char)
			return false
	
	var beast_data = owned_phantom_beasts[beast_id]
	var old_name = get_phantom_beast_display_name(beast_id)
	beast_data["custom_name"] = trimmed_name
	
	phantom_beast_renamed.emit(beast_id, trimmed_name)
	# 数据将在下次自动保存或手动保存时保存
	
	print("幻兽改名成功: %s -> %s" % [old_name, get_phantom_beast_display_name(beast_id)])
	return true

func reset_phantom_beast_name(beast_id: String) -> bool:
	"""重置幻兽名称为默认名称"""
	if not owned_phantom_beasts.has(beast_id):
		print("错误：未找到幻兽 %s" % beast_id)
		return false
	
	var beast_data = owned_phantom_beasts[beast_id]
	var old_name = get_phantom_beast_display_name(beast_id)
	beast_data["custom_name"] = ""
	
	phantom_beast_renamed.emit(beast_id, beast_data["name"])
	# 数据将在下次自动保存或手动保存时保存
	
	print("幻兽名称已重置: %s -> %s" % [old_name, get_phantom_beast_display_name(beast_id)])
	return true

func get_phantom_beast_display_name(beast_id: String) -> String:
	"""获取幻兽显示名称（优先显示昵称）"""
	if not owned_phantom_beasts.has(beast_id):
		return "未知幻兽"
	
	var beast_data = owned_phantom_beasts[beast_id]
	var custom_name = beast_data.get("custom_name", "")
	if custom_name != "":
		return custom_name
	else:
		return beast_data.get("name", "未知幻兽")

func get_phantom_beast_full_info(beast_id: String) -> Dictionary:
	"""获取幻兽完整信息（包括生命值和名称）"""
	if not owned_phantom_beasts.has(beast_id):
		return {}
	
	var beast_data = owned_phantom_beasts[beast_id].duplicate()
	var stats = get_phantom_beast_stats(beast_id)
	
	# 确保包含unique_id字段
	if not beast_data.has("unique_id"):
		beast_data["unique_id"] = beast_id
	
	# 添加计算后的属性
	beast_data["stats"] = stats
	beast_data["display_name"] = get_phantom_beast_display_name(beast_id)
	beast_data["in_formation"] = active_formation.has(beast_id)
	beast_data["hp_percentage"] = get_phantom_beast_hp_percentage(beast_id)
	
	return beast_data

func get_phantom_beast_config(monster_type: String) -> Dictionary:
	"""获取幻兽配置信息"""
	if phantom_beast_config.has(monster_type):
		return phantom_beast_config[monster_type]
	else:
		print("警告：未找到幻兽配置 %s" % monster_type)
		# 如果配置为空，尝试重新加载
		if phantom_beast_config.is_empty():
			_load_phantom_beast_config()
			if phantom_beast_config.has(monster_type):
				return phantom_beast_config[monster_type]
		return {}

func get_phantom_beast_config_by_id(beast_id: String) -> Dictionary:
	"""通过幻兽ID获取幻兽配置信息"""
	if not owned_phantom_beasts.has(beast_id):
		print("警告：未找到幻兽 %s" % beast_id)
		return {}
	
	var beast_data = owned_phantom_beasts[beast_id]
	var monster_type = beast_data.get("monster_type", "")
	return get_phantom_beast_config(monster_type)

func _migrate_old_beast_data(old_beasts: Dictionary):
	"""迁移旧版本的幻兽数据到新格式"""
	var migrated_formation: Array[String] = []
	
	for old_beast_id in old_beasts.keys():
		var old_beast_data = old_beasts[old_beast_id]
		
		# 生成新的唯一ID
		var new_unique_id = _generate_unique_beast_id()
		
		# 复制旧数据并添加新字段
		var new_beast_data = old_beast_data.duplicate()
		new_beast_data["unique_id"] = new_unique_id
		
		# 如果旧数据中有"id"字段，将其重命名为"monster_type"
		if new_beast_data.has("id"):
			new_beast_data["monster_type"] = new_beast_data["id"]
			new_beast_data.erase("id")
		
		# 存储到新的字典中
		owned_phantom_beasts[new_unique_id] = new_beast_data
		
		# 更新队伍配置中的ID映射
		if active_formation.has(old_beast_id):
			var formation_index = active_formation.find(old_beast_id)
			if formation_index != -1:
				migrated_formation.append(new_unique_id)
				print("迁移队伍中的幻兽: %s -> %s" % [old_beast_id, new_unique_id])
	
	# 更新队伍配置
	active_formation.clear()
	for new_id in migrated_formation:
		active_formation.append(new_id)
	
	print("数据迁移完成，迁移了 %d 只幻兽" % owned_phantom_beasts.size())
	
	# 数据将在下次自动保存或手动保存时保存

# ========== 幻兽合成系统 ==========

signal phantom_beast_synthesized(beast_id: String, new_star_level: int)

func can_synthesize_beast(main_beast_id: String, material_beast_ids: Array[String]) -> Dictionary:
	"""检查是否可以合成幻兽"""
	var result = {"can_synthesize": false, "reason": ""}
	
	# 检查主幻兽是否存在
	if not owned_phantom_beasts.has(main_beast_id):
		result["reason"] = "主幻兽不存在"
		return result
	
	var main_beast = owned_phantom_beasts[main_beast_id]
	
	# 检查主幻兽是否存活
	if not main_beast.get("is_alive", true):
		result["reason"] = "主幻兽已死亡，无法合成"
		return result
	
	# 检查星级是否已达到上限
	var current_star = main_beast.get("star_level", 1)
	if current_star >= max_star_level:
		result["reason"] = "主幻兽已达到最高星级"
		return result
	
	# 检查副宠数量
	if material_beast_ids.size() != 2:
		result["reason"] = "需要2个副宠进行合成"
		return result
	
	# 检查副宠
	for material_id in material_beast_ids:
		if not owned_phantom_beasts.has(material_id):
			result["reason"] = "副宠不存在"
			return result
		
		var material_beast = owned_phantom_beasts[material_id]
		
		# 检查副宠是否存活
		if not material_beast.get("is_alive", true):
			result["reason"] = "副宠已死亡，无法合成"
			return result
		
		# 检查是否为同类型
		if material_beast.get("monster_type") != main_beast.get("monster_type"):
			result["reason"] = "副宠必须与主宠为同一类型"
			return result
		
		# 检查星级是否匹配
		if material_beast.get("star_level", 1) != current_star:
			result["reason"] = "副宠星级必须与主宠相同"
			return result
		
		# 检查等级要求
		if main_beast.get("level", 1) < material_beast.get("level", 1):
			result["reason"] = "主宠等级必须大于或等于副宠等级"
			return result
	
	# 检查金币是否足够
	var synthesis_cost = calculate_synthesis_cost(current_star)
	if PlayerStatsManager.get_gold() < synthesis_cost:
		result["reason"] = "金币不足，需要 " + str(synthesis_cost) + " 金币"
		return result
	
	result["can_synthesize"] = true
	return result

func calculate_synthesis_cost(current_star: int) -> int:
	"""计算合成费用"""
	return synthesis_cost_base * current_star * current_star

func synthesize_beast(main_beast_id: String, material_beast_ids: Array[String]) -> bool:
	"""执行幻兽合成"""
	var check_result = can_synthesize_beast(main_beast_id, material_beast_ids)
	if not check_result["can_synthesize"]:
		print("合成失败: ", check_result["reason"])
		return false
	
	var main_beast = owned_phantom_beasts[main_beast_id]
	var current_star = main_beast.get("star_level", 1)
	
	# 扣除金币
	var synthesis_cost = calculate_synthesis_cost(current_star)
	PlayerStatsManager.add_gold(-synthesis_cost)
	
	# 移除副宠
	for material_id in material_beast_ids:
		# 从队伍中移除
		remove_from_formation(material_id)
		# 删除副宠
		owned_phantom_beasts.erase(material_id)
	
	# 升级主宠星级
	main_beast["star_level"] = current_star + 1
	
	# 更新主宠的最大生命值和当前生命值
	var new_stats = get_phantom_beast_stats(main_beast_id)
	main_beast["max_hp"] = new_stats["max_hp"]
	main_beast["current_hp"] = new_stats["max_hp"]  # 合成后满血
	
	print("合成成功！", main_beast["name"], " 升级到 ", main_beast["star_level"], " 星")
	phantom_beast_synthesized.emit(main_beast_id, main_beast["star_level"])
	# 数据将在下次自动保存或手动保存时保存
	return true

func save_data() -> Dictionary:
	"""保存幻兽管理器数据"""
	return {
		"owned_phantom_beasts": owned_phantom_beasts,
		"active_formation": active_formation,
		"next_beast_id": next_beast_id
	}

func load_data(data: Dictionary) -> void:
	"""加载幻兽管理器数据"""
	owned_phantom_beasts = data.get("owned_phantom_beasts", {})
	active_formation = data.get("active_formation", [])
	next_beast_id = data.get("next_beast_id", 1)
	
	# 确保加载的数据格式正确
	for beast_id in owned_phantom_beasts.keys():
		var beast_data = owned_phantom_beasts[beast_id]
		# 确保所有必要字段存在
		if not beast_data.has("is_alive"):
			beast_data["is_alive"] = true
		if not beast_data.has("current_hp"):
			beast_data["current_hp"] = beast_data.get("base_hp", 50)
		if not beast_data.has("star_level"):
			beast_data["star_level"] = 1  # 为旧数据添加星级字段
